namespace HEFramework
{
    /// <summary>
    ///
    /// 公共文件流
    /// 
    /// ----------------------------------------
    /// 作者 hep
    /// 创建时间：2023-12-19 17:38:49
    /// ----------------------------------------
    /// </summary>
    public class CommonFileStream : IFileStream
    {
        public void WriteBytesSyn(string _filePath, byte[] _bytes)
        {
            if (_bytes == null)
            {
                Log.Error("Bytes is null");
                return;
            }

            string path = System.IO.Path.GetDirectoryName(_filePath);
            string name = System.IO.Path.GetFileName(_filePath);
            CreateDirectory(path);
            string olds = path + "/" + "temp_" + name;
            string news = _filePath;

            System.IO.File.WriteAllBytes(olds, _bytes);
            System.IO.File.Copy(olds, news, true);
            DeleteFile(olds);
        }

        public async HETask WriteBytesAsync(string _filePath, byte[] _bytes, HECancellationToken _cancellationToken = null, int _bufferSize = 4096)
        {
            string path = System.IO.Path.GetDirectoryName(_filePath);
            string name = System.IO.Path.GetFileName(_filePath);
            CreateDirectory(path);
            string olds = path + "/" + "temp_" + name;
            string news = _filePath;

            using (System.IO.FileStream fileStream = new System.IO.FileStream(olds, System.IO.FileMode.Create, System.IO.FileAccess.Write))
            {
                using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(_bytes))
                {
                    Buffer buffer = Buffer.Get(_bufferSize);
                    int length;
                    while ((length = await memoryStream.ReadAsync(buffer.Bytes, 0, buffer.Size)) > 0)
                    {
                        if (_cancellationToken.IsCancel())
                        {
                            return;
                        }

                        await fileStream.WriteAsync(buffer.Bytes, 0, length);
                    }

                    Buffer.Put(buffer);
                }
            }

            System.IO.File.Copy(olds, news, true);
            DeleteFile(olds);
        }

        public byte[] ReadBytesSyn(string _filePath)
        {
            if (!CheckFile(_filePath))
            {
                return null;
            }

            using (System.IO.FileStream fileStream = new System.IO.FileStream(_filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read))
            {
                byte[] bytes = new byte[fileStream.Length];
                fileStream.Read(bytes, 0, (int)fileStream.Length);
                return bytes;
            }
        }

        public async HETask<byte[]> ReadBytesAsync(string _filePath, HECancellationToken _cancellationToken = null, int _bufferSize = 4096)
        {
            if (!CheckFile(_filePath))
            {
                return null;
            }

            using (System.IO.FileStream fileStream = new System.IO.FileStream(_filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read))
            {
                using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
                {
                    Buffer buffer = Buffer.Get(_bufferSize);
                    int length;
                    while ((length = await fileStream.ReadAsync(buffer.Bytes, 0, buffer.Size)) > 0)
                    {
                        if (_cancellationToken.IsCancel())
                        {
                            return null;
                        }

                        await memoryStream.WriteAsync(buffer.Bytes, 0, length);
                    }

                    Buffer.Put(buffer);
                    return memoryStream.ToArray();
                }
            }
        }

        public bool CheckFile(string _filePath)
        {
            if (System.IO.File.Exists(_filePath))
            {
                return true;
            }

            return false;
        }

        public bool DeleteFile(string _filePath)
        {
            if (System.IO.File.Exists(_filePath))
            {
                System.IO.File.Delete(_filePath);
                return true;
            }

            return false;
        }

        public bool CreateDirectory(string _path)
        {
            if (!System.IO.Directory.Exists(_path))
            {
                System.IO.Directory.CreateDirectory(_path);
            }

            return true;
        }

        public bool DeleteDirectory(string _path)
        {
            try
            {
                // 确保目录存在
                if (System.IO.Directory.Exists(_path))
                {
                    // 删除目录中的所有文件
                    string[] files = System.IO.Directory.GetFiles(_path);
                    foreach (string file in files)
                    {
                        System.IO.File.SetAttributes(file, System.IO.FileAttributes.Normal); // 将文件属性设置为正常，确保文件不是只读
                        System.IO.File.Delete(file);
                    }

                    // 递归删除所有子目录
                    string[] subDirs = System.IO.Directory.GetDirectories(_path);
                    foreach (string subDir in subDirs)
                    {
                        DeleteDirectory(subDir);
                    }

                    // 删除现在空的目录
                    System.IO.Directory.Delete(_path, false);
                }
            }
            catch (System.Exception e)
            {
                return false;
            }

            return true;
        }
    }
}